<?php
namespace app\admin\controller;
use app\admin\common\Base;
use think\Db;
use think\facade\Request;
use think\Exception;
use app\admin\model\Order as OrderModel;
use app\admin\model\ServiceItem as ServiceItemModel;
use app\admin\model\Merchant as MerchantModel;
use app\admin\model\MerchantService as MerchantServiceModel;
use app\admin\model\AdminUser as AdminUserModel;
use app\admin\model\MerchantOverarea as MerchantOverareaModel;

/**
 * 订单控制器
 */
class Order extends Base{

    use \app\admin\traits\BaseFn;

    protected $model = null;

    public function initialize(){
        parent::initialize();
        $this->model = new OrderModel();
    }

    /**
     * 列表
     */
    public function index(){
        $userInfo = session('admin');
        $roleIds = explode(',', $userInfo['role_ids']);
        $fineshedEditable = 0;  //是否可以编辑【已完成】的订单
        if( in_array('1', $roleIds) || in_array('2', $roleIds) || in_array('3', $roleIds) ){
            $fineshedEditable = 1;
        }
        $this->assign('fineshedEditable', $fineshedEditable);

        if(Request::isAjax()){

            list($where,$sort) = $this->buildQuery();
            if(empty($sort)) $sort = ['id'=>'desc'];    //【默认排序】



            $wherePriv = [];
            if(in_array('1', $roleIds) || in_array('2', $roleIds)){ //【超级管理员】和【会计】角色查看客户资料无需条件限制
                ;
            }else if(count($roleIds)==1 && $roleIds[0] == '4'){ //【客服】角色只能查看自己的客户
                $wherePriv[] = ['create_user_id', '=', $userInfo['id'], ];
            }else if( in_array('3', $roleIds) ){ //【组长】角色可以看到自己和自己下属的客户
                $lowerLevelIds  = AdminUserModel::where(['leader'=> $userInfo['id']])->column('id');
                array_unshift($lowerLevelIds, $userInfo['id']);
                $wherePriv[] = ['create_user_id', 'in', $lowerLevelIds, ];
            }else{
                $wherePriv[] = ['1', '=', '0']; //其余角色不让看到数据
            }


            $list = $this->model->alias('t1')
                ->leftjoin('client t2', 't1.client_id=t2.id')   //客户表
                ->leftjoin('merchant t3', 't1.mch_id=t3.id') //商家
                ->leftjoin('admin_user t4', 't1.create_user_id=t4.id') //坐席用户表
                ->field('t1.*')
                ->field('t2.client_name,t2.phone')
                ->field('t3.name,t3.mch_province,t3.mch_city,t3.mch_area,t3.contact_phone') //商家
                ->field('t4.nickname')
                ->where('t1.is_del', 0)
                ->where($where)
                ->where($wherePriv)     //按角色 过滤
                ->order($sort)
                ->paginate(Request::param('pageSize'))
                ->toArray();
            foreach($list['data'] as &$row){
                $row['contact_phone'] = (array)(da_jdecode($row['contact_phone'], true));
            }
            unset($row);

            $data = [
                "total"=>$list['total'],
                'rows'=>$list['data'],
            ];
            return json($data);
        }

        //订单状态
        $order_status = \Config::get('sysarray.order_status');
        $this->assign('order_status', $order_status);

        //editable插件
        $orderStatus = [];
        foreach ($order_status as $val=>$status){
            $orderStatus[] = [
                'value'=> $val,
                'text'=> $status,
            ];
        }
        $this->assign('orderStatus', $orderStatus);

        //查询所有服务
        $srvItemHash = ServiceItemModel::column('service_name', 'id');
        $srvItemHash['others'] = '未分配';
        //$this->assign('srvItemHash', da_jencode($srvItemHash));
        $this->assign('srvItemHash', $srvItemHash); //在前端采用： {$srvItemHash | da_jencode |raw}

        return $this->fetch();
    }


    //展示客户的5个历史订单
    public function clientOrder(){
        if(Request::isAjax()){
            $client_id = $this->request->post('client_id', -1); //新客户弹屏无 client_id
            $order_phone = $this->request->post('order_phone', '', 'trim');

            $order_status = \Config::get('sysarray.order_status');

            //查询所有服务
            $srvItemHash = ServiceItemModel::column('service_name', 'id');
            //$this->assign('srvItemHash', $srvItemHash);

            $rows = $this->model->alias('t1')
                ->leftjoin('client t2', 't1.client_id=t2.id')   //客户表
                ->leftjoin('merchant t3', 't1.mch_id=t3.id') //商家
                ->leftjoin('admin_user t4', 't1.create_user_id=t4.id') //坐席用户表
                ->field('t1.*')
                ->field('t2.client_name,t2.phone')
                ->field('t3.name,t3.contact_phone,t3.mch_province,t3.mch_city,t3.mch_area') //商家
                ->field('t4.nickname')
                ->where('t1.is_del', 0)
                ->where(function($query) use($client_id, $order_phone){
                    $query->where('client_id', $client_id)->whereOr('order_phone', $order_phone);
                })
                ->order('create_time desc')
                ->limit(5)
                ->select();
            foreach($rows as &$item){
                $item['srv_item'] = isset($srvItemHash[ $item['srv_item_id'] ])? $srvItemHash[ $item['srv_item_id'] ] : '';
                $item['order_status_val'] = $order_status[ $item['order_status'] ];
                $item['contact_phone'] = (array)(da_jdecode($item['contact_phone'], true));
                $item['contact_phone'] = array_diff($item['contact_phone'], ['']);  //去除空元素
            }
            unset($item);
            $this->assign('rows', $rows->toArray($rows));

            return $this->fetch();
        }

    }


    /**
     * 查看订单详情
     */
    public function detail(){
        //订单状态
        $order_status = \Config::get('sysarray.order_status');
        $this->assign('order_status', $order_status);

        $where = Request::param();
        $data = $this->model->where($where)->find();
        if(empty($data['service_time']))
            $data['service_time'] = '';
        else
            $data['service_time'] = date('Y-m-d H:i:s', $data['service_time']);

        //服务项目
        if($data['srv_item_id']){
            $data['srv_item_id_val'] = ServiceItemModel::where(['id'=>$data['srv_item_id'],])->value('service_name');
        }else{
            $data['srv_item_id_val'] = '';
        }

        //商家
        if($data['mch_id']){
            $data['merchantInfo'] = MerchantModel::where(['id'=>$data['mch_id'],])->field('mch_province,mch_city,mch_area,contact_phone')->find();
        }else{
            $data['merchantInfo'] = ['mch_province'=>'', 'mch_city'=>'', 'mch_area'=>'', 'contact_phone'=>''];
        }

        $this->assign('data',$data);
        return $this->fetch();
    }

    /**
     * 编辑
     */
    public function edit(){
        if(Request::isAjax()){
            $code = 0;
            $msg = 'success';
            $data = null;
            try{
                $where = [
                    'id'=>Request::param('id'),
                ];
                $update = Request::except('id');

                foreach ($update as $key=>$value){
                    if(substr($key,-4) === 'time'){
                        $update[$key] = strtotime($value);
                    }
                }

                if( !isset($_GET['editable']) ){
                    //已接单之后的订单必须选择商家
                    if( $update['order_status'] > 1 ){
                        if( empty($update['mch_id']) ){
                            throw new Exception('请选择服务商家！');
                        }
                    }

                    if( $update['order_status'] == 99 ){
                        if( empty($update['fee']) ){
                            throw new Exception('订单服务费用必需填写！');
                        }
                    }
                    $update['fee'] = floatval($update['fee']);

                }else{
                    //如果采用x-edit编辑插件修改状态，必须检测
                    $ord = $this->model->get($this->request->get('id'));

                    //修改为已完成状态必须填写金额
                    if( $update['order_status'] == 99 ){
                        if( empty($ord['fee']) || abs($ord['fee']) < 0.00001 ){
                            throw new Exception('状态修改失败：订单服务费用必需填写！');
                        }
                    }

                }



                //服务商家范围匹配
                if(!empty($update['mch_id'])){
                    $myArea = isset($update['area'])? $update['area']: '';  //需要检查的服务范围

                    $map = [
                        'mch_id' => $update['mch_id'],
                        'srv_province' => $update['province'],
                        'srv_city' => isset($update['city'])? $update['city']: '',
                    ];
                    if( mb_substr($update['province'],-1,null, 'utf-8')=='市' ){  //直辖市
                        $map['srv_city'] = $map['srv_province'];
                        $myArea = isset($update['city'])? $update['city']: '';
                    }
                    $overarea = MerchantOverareaModel::where($map)->field('srv_areas')->find();
                    if( empty($overarea) ){
                        throw new Exception('客户所在区域不在所选商家服务范围！');
                    }
                    $areas = da_jdecode($overarea['srv_areas'], true);
                    if(! in_array($myArea, (array)$areas) ){
                        throw new Exception('客户所在区域不在所选商家服务范围！');
                    }
                }



                $this->model->save($update,$where);
                $msg = "保存成功";

            }catch (Exception $e){
                $code = 500;
                $msg = $e->getMessage();
            }

            return json(['data'=>$data,'msg'=>$msg,'code'=>$code]);
        }


        $srvItems = ServiceItemModel::where(['status'=>1])->field(['id', 'service_name'])
            ->order('id asc')->select();
        $this->assign('srvItems', $srvItems);
        //订单状态
        $order_status = \Config::get('sysarray.order_status');
        $this->assign('order_status', $order_status);

        //订单数据
        $where = Request::param();
        $data = $this->model->where($where)->find();
        if(empty($data['service_time']))
            $data['service_time'] = time();
        $data['service_time'] = date('Y-m-d H:i:s', $data['service_time']);
        $this->assign('data',$data);


        //所有启用商家
        $match = [];    //基本匹配的商家
        $merchs = MerchantModel::where(['status'=>1, 'is_del'=>0])
            ->field(['id', 'name', 'contact_phone', 'mch_province', 'mch_city', 'mch_area',])->order('id asc')->select();
        $rows = [];    //不匹配的商家
        foreach ($merchs as &$merch){
            $row = [
                'id' => $merch['id'],
                'name' => $merch['name']
                    //.' -- '
                    .' ('.$merch['mch_province'].$merch['mch_city'].$merch['mch_area'] .')',
            ];

            //默认优先展示显示所在地商家
            if($merch['mch_province'] == $data['province'] && $merch['mch_city'] == $data['city']){
                if($merch['mch_area'] == $data['area']){   //完全匹配的，放到最前面
                    array_unshift($match, $row);
                }else{
                    //部分匹配
                    $match[] = $row;
                }
            }else{
                //如果省匹配
                if($merch['mch_province'] == $data['province']){
                    array_unshift($rows, $row);
                }else{
                    $rows[] = $row;
                }
            }

        }
        //$this->assign('merchs', $merchs);
        $this->assign('merchs', array_merge($match, $rows));


        return $this->fetch();
    }

    //删除
    public function softDel(){
        $code = 0;
        $msg = 'success';
        $data = null;
        try{
            if(Request::isAjax()){
                $ids = Request::param('ids');
                if(empty($ids)){
                    $code = 10001;
                    throw new Exception('缺少参数');
                }
                //批量删除--软删除
                $delete_count = $this->model
                    ->where([
                        ['id','in',$ids]
                    ])->update(['is_del'=>1]);

                if($delete_count > 0){
                    $msg = '操作成功';
                }else{
                    $code = 10002;
                    throw new Exception('删除失败');
                }

            }else{
                $code = 10001;
                throw new Exception('请求失败');
            }
        }catch (Exception $e){
            $code = 500;
            $msg = $e->getMessage();
        }

        return json(['data'=>$data,'msg'=>$msg,'code'=>$code]);

    }

}
